package com.rtx.wcs.std.handle.ristowcs.pcbz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.edi.model.api.bo.ApiMappingInfoBo;
import com.rtx.edi.platform.synctask.service.ConvertService;
import com.rtx.wcs.std.bean.po.EdiTaskDownLog;
import com.rtx.wcs.std.bean.po.TaskDetail;
import com.rtx.wcs.std.handle.ristowcs.AbsTaskDownHandle;
import com.rtx.wcs.std.service.TaskDetailService;

import cn.hutool.core.util.StrUtil;


/**
 * PC-播种
 * @author Administrator
 *
 */
@Service("PC-BZ")
public class AbsPCBZTaskDownHandle extends AbsTaskDownHandle<TaskDetail>{
	
	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	TaskDetailService taskDetailService;
	
	@Autowired
	ConvertService convertService;
	
	@Override
	protected void updStatus(TaskDetail o,String response,String mappingcode) {
		
		//处理响应
		Map<String,String> resultMap = handleResponse(o,response,mappingcode);
		
		
		LambdaUpdateWrapper<TaskDetail> upd = Wrappers.lambdaUpdate();
		upd.eq(TaskDetail::getSerialkey, o.getSerialkey());
		upd.set(TaskDetail::getEditflag, resultMap.get("editflag"));
		upd.set(TaskDetail::getMessage, StrUtil.sub(resultMap.get("message"), 0, 499));
		if(StringUtils.hasLength(resultMap.get("data"))) {
			upd.set(TaskDetail::getTaskcode, resultMap.get("data"));
		}else {
			upd.set(TaskDetail::getTaskcode, o.getTaskcode());
		}
		
		taskDetailService.updByCondition(o.getWhseid(),upd);
		
		if(!"PS".equals(resultMap.get("editflag"))) {
			throw new RuntimeException("wcs返回错误-"+resultMap.get("message"));
		}
	}
	
	/**
	 * 解析返回报文
	 * @param data
	 */
	protected Map<String,String> handleResponse(TaskDetail o,String response,String mappingcode){
		Map<String,String> resultMap = new HashMap<>();
		resultMap.put("editflag", "");//PS为成功 PE为失败
		resultMap.put("message", "");
		resultMap.put("data", "");
		resultMap.put("status", "");
		
		try {
			JSONObject res = JSON.parseObject(response);
			if("0".equals(res.getString("code"))) {
				resultMap.put("editflag", "PS");
			}else {
				resultMap.put("editflag", "PE");
			}
			resultMap.put("message", res.getString("msg"));
			resultMap.put("data", o.getTaskcode());
		} catch (Exception e) {
			logger.error("",e);
			resultMap.put("message", response);
			resultMap.put("editflag", "PE");
		}finally {
			resultMap.put("data", o.getTaskcode());
		}
		return resultMap;
	};


	//{"whseid":"仓库号","wavekey":"波次号","rtxtaskgrp":"任务组号","fromloc":"自库位"}
	@Override
	protected List<TaskDetail> queryToSendDataByRISWmsCondition(String request) {
		List<TaskDetail> allList = new ArrayList<TaskDetail>();
		List<JSONObject> list = JSON.parseArray(request,JSONObject.class);
		for(JSONObject data:list) {
			QueryWrapper<TaskDetail> qw = Wrappers.query();
			qw.eq("whseid", data.getString("whseid"));
			qw.eq("wavekey", data.getString("wavekey"));
			qw.eq("rtxtaskgrp", data.getString("rtxtaskgrp"));
			qw.eq("fromloc", data.getString("fromloc"));
			qw.eq("status", "0");
			qw.eq("editflag", "P");
			qw.exists("select 1 from loc where loc =taskdetail.fromloc and locationcategory ='LK' and locationtype ='WCS' ");
			
			allList.forEach(temp->{temp.setToStationCode(data.getString("toStationCode"));});
			
			List<TaskDetail> taskDetail = taskDetailService.queryByCondition(data.getString("whseid"), qw);
			allList.addAll(taskDetail);
			
		}
		
		allList.forEach(temp->{
			if(!StringUtils.hasLength(temp.getTaskcode())) {
				temp.setTaskcode(UUID.randomUUID().toString());
			}
		}
	    );
		return allList;
	}


	@Override
	protected String getapiname(String request) {
		return "PC-播种";
	}


	@Override
	protected void mappingReqToLog(TaskDetail data, EdiTaskDownLog log) {
		log.setType("CTUJH");
		log.setLpn(data.getFromid());
		log.setPositioncode(data.getFromloc());
		log.setLoc(data.getToloc());
		log.setTaskcode(data.getTaskcode());
	}
	
	@Override
	protected JSONObject converWcsRequest(TaskDetail t, String mappingcode) {
		String source = JSON.toJSONString(t);
		String targetjson = convertService.ConvertByMappingCodeAndSource(mappingcode, source);
		return JSON.parseObject(targetjson);
	}

	@Override
	protected String getEdiRequestURL(String mappingcode) {
		ApiMappingInfoBo bo = convertService.getConfigByApimappingcode(mappingcode);
		return bo.getTargetUrl();
	}
	
}
